package com.changyou.skynet.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.changyou.skynet.pageModel.SessionInfo;
import com.changyou.skynet.pageModel.User;
import com.changyou.skynet.service.UserServiceI;
import com.changyou.skynet.util.ConfigUtil;
import com.changyou.skynet.util.IpUtil;
import com.changyou.skynet.web.domain.page.Json;

@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserServiceI userService;

    @ResponseBody
    @RequestMapping("/login")
    public Json login(User user, HttpSession session, HttpServletRequest request) {
        Json j = new Json();
        User u = userService.login(user);
        if (null != u) {
            j.setSuccess(true);
            j.setMsg("登陆成功");

            SessionInfo sessionInfo = new SessionInfo();
            BeanUtils.copyProperties(u, sessionInfo);
            sessionInfo.setIp(IpUtil.getIpAddr(request));
            sessionInfo.setResourceList(userService.resourceList(u.getId()));
            session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);
            j.setObj(sessionInfo);
        } else {
            j.setMsg("用户名或密码错误！");
        }
        return j;
    }

    @ResponseBody
    @RequestMapping("/reg")
    public Json reg(User user) {
        Json j = new Json();
        try {
            userService.reg(user);
            j.setSuccess(true);
            j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
            j.setObj(user);
        } catch (Exception e) {
            // e.printStackTrace();
            j.setMsg(e.getMessage());
        }
        return j;
    }
}
